package com.assistant.core.modules.sys.adapter;

import com.assistant.core.modules.sys.BusinessContext;
import com.assistant.core.modules.sys.domain.user.JWTHelper;
import com.assistant.core.modules.sys.domain.user.Token;
import com.assistant.core.modules.sys.domain.user.User;
import com.assistant.core.modules.sys.domain.user.gateway.UserGateway;
import com.assistant.exception.AssistantException;
import com.assistant.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录拦截器
 */
@Component
public class AssistantLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserGateway operatorGateway;
    @Autowired
    private JWTHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        final String xToken = request.getHeader("X-Token");
        if (StringUtils.hasLength(xToken)) {
            final Token token = jwtHelper.genToken(xToken);
            final User loginUser = operatorGateway.getById(token.getId());
            BusinessContext.setOperator(loginUser);
        } else {
            throw new AssistantException("没有登录");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        BusinessContext.remove();
    }
}
